// Copyright (C) 2022 Huawei Device Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package controllers

import (
	"dist/model"
	"dist/services"
	"dist/utils"
	"fmt"
	"net/http"
)

func Visit(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		utils.Resp(w)(0, "success", map[string]interface{}{})
		return
	}
	ip, _ := utils.GetIP(r)
	uid := utils.Encrypt(ip)
	var req model.VisitReq
	err := utils.RequestToStruct(r, &req)
	error := utils.CheckParameters(&req)
	if error != nil {
		utils.Resp(w)(-1, fmt.Sprintf("%v", error), map[string]interface{}{})
		return
	}
	effectiveAccess := false
	if err == nil {
		if req.VisitId > 0 {
			effectiveAccess = true
		}
	}
	res, accessId := services.UserVisit(uid, effectiveAccess, req.VisitId)
	if res {
		if effectiveAccess {
			utils.Resp(w)(0, "success", map[string]interface{}{})
		} else {
			utils.Resp(w)(0, "success", accessId)
		}
	} else {
		utils.Resp(w)(-1, "failed", map[string]interface{}{})
	}
}

func HomePage(w http.ResponseWriter, r *http.Request) {
	visitData := services.GetHomePageVisitCollection()
	userData := services.GetHomePageUserCollection()
	data := utils.MergeArray(userData, visitData)
	if data != nil {
		utils.Resp(w)(0, "success", data)
	} else {
		utils.Resp(w)(-1, "get failed", map[string]interface{}{})
	}
}

func HomePageChart(w http.ResponseWriter, r *http.Request) {
	var req model.TimeRangeWithIntervalReq
	err := utils.RequestToStruct(r, &req)
	error := utils.CheckParameters(&req)
	if error != nil {
		utils.Resp(w)(-1, fmt.Sprintf("%v", error), map[string]interface{}{})
		return
	}
	if err == nil {
		datas := services.GetHomePageChar(utils.TsToTime(req.StartTime), utils.TsToTime(req.EndTime), req.Interval)
		if datas != nil {
			utils.Resp(w)(0, "success", datas)
		} else {
			utils.Resp(w)(-1, "get failed", map[string]interface{}{})
		}
	} else {
		utils.Resp(w)(-1, fmt.Sprintf("%v", err), map[string]interface{}{})
	}
}
